var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var indexRouter = require('./routes/Web/index');
var authRouter = require('./routes/Web/auth');
//导入accounts接口路由文件
const accountsRouter = require('./routes/api/account');

//导入mongodb模块--- 获取里面的数据库名称等信息
const {dbHost, dbPost, dbName} = require('./model/mongodb')

//导入express-session
const session = require('express-session');
// 导入connect-mongo  ---  用来连接mongodb服务器
const connectMongo = require('connect-mongo');

var app = express();

// 设置session中间件
app.use(session({
    name: 'sid',//设置cookie的name(用户发送信息后服务器返回的一个cookie_id)
    secret: 'lk',//参加加密的字符串(又称签名) -- 加盐
    saveUninitialized: false,//是否为每次请求都设置一个cookie用来存储session的id
    resave: true,//是否在每次请求时都重新保存session过期的时间
    store: connectMongo.create({
        mongoUrl: `mongodb://${dbHost}:${dbPost}/${dbName}`//连接数据库的配置
    }),
    cookie: {//服务器返回的数据
        httpOnly: true,//开启后前端无法通过js操作
        maxAge: 1000 * 60 * 10 * 24 * 7//控制 sessionID 过期的时间
    }
}));

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({extended: false}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/', authRouter);
app.use('/api', accountsRouter);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
    res.render('404')
});
//方法二 catch 404 and forward to error handler
// app.all('*',(req, res) => {
//     res.render('404')
// });
// error handler
app.use(function (err, req, res, next) {
    // set locals, only providing error in development
    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};

    // render the error page
    res.status(err.status || 500);
    res.render('error');
});

module.exports = app;
